package com.starblink.store.view

import android.util.Log
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.widget.dialog.BaseBottomSheetFragment
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.fragment.BrotherOfferF
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.store.databinding.DialogCompareProductBinding
import com.starblink.store.databinding.ItemCompareProductViewBinding

class StoreProductCompareDialog(
    val context: FragmentActivity,
    var curProduct: ProductF,
    val list: List<ProductF.BrotherOffer?>?,
    private val ifEqualHaveTag: Boolean = false, //是否相等时也打最低价标签,
    val trackPage: Int = SpmPageDef.StoresComparedBottomSheet, // 埋点：页面追踪
    val searchTerm: String = "", // 埋点：搜索关键词
) : BaseBottomSheetFragment() {

    var productList = mutableListOf<BrotherOfferF>()
    lateinit var mBinding: DialogCompareProductBinding
    override fun getBindingRootView(): View {
        mBinding = DialogCompareProductBinding.inflate(layoutInflater)
        return mBinding.root
    }

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(productList).apply {
            addVhDelegate {
                ItemCompareProductView(
                    binding = ItemCompareProductViewBinding.inflate(it.inflater, it, false),
                    context = context,
                    trackPage = trackPage,
                    searchTerm = searchTerm
                )
            }
        }
    }

    override fun initView() {
        initData()
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.pageExposure.value,
                spmCnt = GTrackerAssistUtils.fetchPageValue(SpmPageDef.StoresComparedBottomSheet),
                params = mapOf()
            )
        )
        var height = productList.size * 72 + 56 + 50 + +80
        setPeekHeight(height.dp2px())
        mBinding.title.text =
            "${CommUtils.getString(com.starblink.basic.style.R.string.compare_price_at)} ${productList.size} ${
                CommUtils.getString(com.starblink.basic.style.R.string.stores)
            }"
        mBinding.close.setOnClickListener {
            dismiss()
        }

        mBinding.recyclerView.layoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.setHasFixedSize(true)
        mBinding.recyclerView.itemAnimator = null
        mBinding.recyclerView.adapter = adapter//单位px


        //同步订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            for (i in productList.indices) {
                val item = productList[i]
                if (event.id != null && event.id == item.merchantWeb?.id
                    && event.followed != item.merchantWeb!!.subOrNot
                ) {
                    ApolloValSetExt.setApolloVal<BrotherOfferF.MerchantWeb>(
                        item.merchantWeb!!,
                        "subOrNot",
                        event.followed
                    )
                    Log.e("StoreProductCompare", "====111=${item.merchantWeb}")
                    productList[i] = item
                    adapter.notifyDataSetChanged()
                    break
                }
            }

        }

    }

    private fun initData() {
        val price = curProduct.price ?: 0.0
        val product = curProduct.toJson().toBean<BrotherOfferF>()
        var product0: ProductF.BrotherOffer? = list!!.first()

        val price0 = product0?.brotherOfferF?.price ?: 0.0
        if (price.compareTo(price0) < 0 || (ifEqualHaveTag && price.compareTo(price0) == 0)) {
            //品牌合集详情价格相等时需要打标签 店铺搜索价格相等时不需要打标签 品牌合集详情ifEqualHaveTag=true
            //如果当前sale商品价格低于或等于brother第一个商品 将当前sale打标 brother去掉打标 品牌合集详情brother第一个商品不是最低价minimumPriceFlag=true
            ApolloValSetExt.setApolloVal<BrotherOfferF>(product, "minimumPriceFlag", true)
            product0?.brotherOfferF?.let {
                ApolloValSetExt.setApolloVal<BrotherOfferF>(
                    it,
                    "minimumPriceFlag",
                    false
                )
            }
        }

        productList.add(0, product)
        list.forEach { it ->
            it?.let { it1 -> productList.add(it1.brotherOfferF) }
        }
        adapter.notifyDataSetChanged()
    }
}